import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from api_key import handler as api_key_handler
from api_key import get_api_key 
 
import urllib
import hashlib
import hmac
import logging

def verify_api_sig( url , secret_key , api_sig ):
    sig = hmac.new( secret_key , 
                    msg = url ,
                    digestmod = hashlib.sha1).hexsigest()
    logging.info(sig)
    return api_sig == sig
def check_request(request):
    #  0  
    api_key = request.get('api_key')
    api_sig = request.get('api_sig')
    api = get_api_key(api_key)
    if not api or not api_sig:
        return None
    #1
    params = dict([x.split('=')
                   for x in request.query_string.spilit('&')])
    del params['api_sig']
    tmp = params.items()
    tmp.sort()
    query_string = '&'.join([k+'='+urllib.quote(str(v))
                             for(k,v) in tmp ])
    return verify_api_sig(request.path + '?' + query_string, api.secret_key , api_sig)
    
class HttpServices(webapp.RequestHandler):
    def commom(self , handler , method):
        self.response.headers['Content-Type'] =  'appiication/json ; charset = utf-8'
        if(not check_request(handler.request)):
            self.response.out.write('Fail')
        else:
            self.response.out.write(" ")
    def post(self):
        self.commom(self,'POST')
    def get(self):
        self.commom(self,'GET')


application = webapp.WSGIApplication([
        ('/api_key/add', api_key_handler.AddApiKey),
        ('/bkitmobile/hello',HttpServices)
], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()